package com.android.GernerateKeySet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;

import android.os.Environment;
import android.util.Log;

public class GenerateKeySet {

	int filelen = 0;
	private PrivateKey PVKey;
	private PublicKey PUKey;
	
	public boolean generateKey(UserInformation info, String pwd){
		char[] enpwd = pwd.toCharArray();
		// 개인키 생성
		byte[] EncodedPVKey = null;
		try {
			GenerateKeyPair keyPair = new GenerateKeyPair();
			setPVKey(keyPair.getPrivateKey());
			setPUKey(keyPair.getPublicKey());
			EncodedPVKey = PVKey.getEncoded();
		} catch (Exception e) {
			e.printStackTrace();

			return false;
		}
		
		/** 개인키를 비밀번호(enpwd)로 암호화 **/

		final PasswrodBasedCrypto pwdcrypt;
		pwdcrypt = new PasswrodBasedCrypto();
		
		byte[] EncryptPVKey = pwdcrypt.getEncryptionText(enpwd,
				EncodedPVKey);
		try {
			// 개인키 Sdcard에 PVKey file에 저장
			String path = Environment.getExternalStorageDirectory()
					.toString()+"/cert";
			Log.d("path", "" + path);
			//FileOutputStream fos = new FileOutputStream(path + "/PVKey");
			FileOutputStream fos = new FileOutputStream(path + "/PV"+info.getCn());
			fos.write(EncryptPVKey);
			filelen = EncryptPVKey.length;
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();

			return false;
		}

		/** CA server에 인증서 요청**/
		//인증서요청서 작성
//		UserInformation info = new UserInformation();
		info.setPublicKey(getPUKey());
		TCPclient socket = new TCPclient();
		socket.requestCert(info);
		
		return true;
		
	}

	private PublicKey getPUKey() {
		// TODO Auto-generated method stub
		return PUKey;
	}

	private void setPUKey(PublicKey publicKey) {
		// TODO Auto-generated method stub
		PUKey = publicKey;
		
	}

	private void setPVKey(PrivateKey privateKey) {
		// TODO Auto-generated method stub
		PVKey = privateKey;
		
	}
	
	
	
}
